<script>
export default {
  name: 'Trademark'
}
</script>
<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { GET_TOKEN } from '@/utils/token'
import $api from '@/api/index'
import { ElMessage } from 'element-plus'

onMounted(() => {
  reqTrademark()
})

// 按钮 + table 表单 主体内容
// 当前分页页码
const page = ref(1)
// 每页显示个数
const limit = ref(3)
// 品牌总个数
const total = ref(0)
// 品牌数据数组
const trademarkArr = ref([])

// 请求品牌数据
async function reqTrademark(page = 1) {
  const result = await $api.product.trademark.reqTrademark(page, limit.value)
  if (result?.data?.code === 200) {
    trademarkArr.value = result.data.data.records
    total.value = result.data.data.total
  } else {
    alert('reqTrademark 请求失败')
  }
}
// 更改显示个数事件
function handleSizeChange() {
  page.value = 1
  reqTrademark()
}
// 更改当前页码事件
function handleCurrentChange() {
  reqTrademark(page.value)
}

// 添加品牌 | 编辑品牌 的对话框
// 添加、编辑 dialog打开判定
const dialogVisible = ref(false)
// 添加、编辑 信息收集表单
// trademarkForm表单DOM
const trademarkFormRef = ref()
// trademarkForm表单验证规则
const validatorLogoUrl = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请您上传品牌LOGO'))
  } else {
    callback()
  }
}
const validatorTmName = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请您输入品牌名称'))
  } else {
    callback()
  }
}
const trademarkFormRules = reactive({
  logoUrl: [{ validator: validatorLogoUrl, trigger: 'blur' }],
  tmName: [{ validator: validatorTmName, trigger: 'change' }]
})
// trademarkForm表单数据收集
const trademarkData = ref({
  logoUrl: '',
  tmName: ''
})

// 打开Dialog
function openDialog(row) {
  // 重置表单
  dialogVisible.value = true
  nextTick(() => {
    // 重置表单
    trademarkFormRef.value.resetFields()
    if (row) Object.assign(trademarkData.value, row)
  })
}
// 关闭dialog
function closeDialog() {
  trademarkData.value = {
    logoUrl: '',
    tmName: ''
  }
  dialogVisible.value = false
}
// 保存dialog
async function saveDialog(formRef) {
  try {
    if (!formRef) return
    // 校验表单
    await formRef.validate()

    // 区分 添加品牌 还是 编辑品牌
    if (trademarkData.value.id) {
      await $api.product.trademark.reqUpdateTrademark(trademarkData.value)
      ElMessage.success('品牌更新成功')
    } else {
      await $api.product.trademark.reqAddTrademark(trademarkData.value)
      ElMessage.success('品牌添加成功')
    }

    // 刷新当前table信息
    await reqTrademark(page.value)
    // 关闭表单
    dialogVisible.value = false
  } catch (error) {
    console.log('表单错误')
  }
}

// 上传图片地址
const imgUpLoadUrl = import.meta.env.VITE_SERVER + '/admin/product/fileUpload'
// 上传图片请求头
const imgUpLoadHeaders = { token: GET_TOKEN() }
// 图片上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
  // 拼接LOGO图片的url
  if (response.code === 200) {
    trademarkData.value.logoUrl =
      import.meta.env.VITE_SERVER + response.data.replace(import.meta.env.VITE_APP_BASE_API, '')
  } else {
    ElMessage.error('图片上传 ' + response.message)
  }
}
// 图片上传前回调,校验用
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只能上传 jpg 或 png 的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('图片必须小于 4Mb !')
    return false
  }
  trademarkFormRef.value.clearValidate('logoUrl')
  return true
}

// 删除事件
const reqDelTrademark = async function (id) {
  try {
    await $api.product.trademark.reqDelTrademark(id)
    ElMessage.success('删除品牌成功')
    // 刷新当前table信息
    await reqTrademark(page.value)
  } catch (error) {
    ElMessage.success('删除品牌失败,' + error)
  }
}
</script>

<template>
  <div>
    <!-- 主题内容 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        icon="Plus"
        @click="openDialog()"
        v-has="'btn.Trademark.add'"
      >
        添加品牌
      </el-button>

      <!-- 表单 -->
      <el-table
        border
        stripe
        class="table_class"
        :data="trademarkArr"
      >
        <el-table-column
          type="index"
          label="序号"
          width="100"
          align="center"
        />
        <el-table-column
          prop="tmName"
          label="品牌名称"
        >
        </el-table-column>
        <el-table-column
          prop="logoUrl"
          label="品牌LOGO"
        >
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              style="width: 150px; height: 150px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              @click="openDialog(row)"
              v-has="'btn.Trademark.update'"
            />
            <el-popconfirm
              width="250"
              :title="`你确定要删除 ${row.tmName} ?`"
              @confirm="reqDelTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  icon="Delete"
                  v-has="'btn.Trademark.remove'"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加品牌 | 编辑品牌 的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="trademarkData.id ? '编辑品牌' : '新增品牌'"
    >
      <el-form
        :model="trademarkData"
        ref="trademarkFormRef"
        :rules="trademarkFormRules"
        style="width: 80%"
        label-width="100px"
      >
        <el-form-item
          label="品牌名字"
          prop="tmName"
          required
        >
          <el-input
            v-model="trademarkData.tmName"
            placeholder="请您输入品牌名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="品牌LOGO"
          prop="logoUrl"
          required
        >
          <el-upload
            class="avatar-uploader"
            :action="imgUpLoadUrl"
            :headers="imgUpLoadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkData.logoUrl"
              :src="trademarkData.logoUrl"
              class="avatar"
            />
            <el-icon
              v-else
              class="avatar-uploader-icon"
              ><Plus
            /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button
          type="primary"
          @click="saveDialog(trademarkFormRef)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
// start
.table_class {
  margin: 20px 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
